package com.starpl.mobile.android.monthunsae.november.activity;

import java.io.UnsupportedEncodingException;
import java.util.regex.Pattern;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Html;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;

import com.starpl.mobile.android.monthunsae.november.R;
import com.starpl.mobile.android.monthunsae.november.command.MonthUnsaeCommand;
import com.starpl.mobile.android.platform.common.base.BaseActivity;
import com.starpl.mobile.android.platform.common.base.BaseApplication;
import com.starpl.mobile.android.platform.common.network.HttpHandler;


/**
 * 회원가입 Activity
 * 
 * @author 우연화
 * @since 2011.03.16
 */
public class JoinActivity extends BaseActivity implements OnClickListener
{
	private Activity mActivity;
	
	private static final int CONTEXT_MENU_0_GMAIL 	= 0;
	private static final int CONTEXT_MENU_1_HANMAIL = 1;
	private static final int CONTEXT_MENU_2_HOTMAIL = 2;
	private static final int CONTEXT_MENU_3_NATE 	= 3;
	private static final int CONTEXT_MENU_4_NAVER 	= 4;
	private static final int CONTEXT_MENU_5_MANUAL 	= 5;
	
	private static final String MAIL_0_GMAIL = "gmail.com";
	private static final String MAIL_1_HANMAIL = "hanmail.net";
	private static final String MAIL_2_HOTMAIL = "hotmail.com";
	private static final String MAIL_4_NAVER = "naver.com";
	private static final String MAIL_3_NATE = "nate.com";
	private static final String MAIL_5_MANUAL = "직접입력";
	
	private EditText mEtId;
	private EditText mEtPassword;
	private EditText mEtNickname;
	private LinearLayout mLlEmailAuto;
	private EditText mEtEmailAuto;
	private EditText mEtEmailManual;
	private Button mBEmailAuto;
	
	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.starpl.platform.common.base.BaseActivity#onCreate(android.os.Bundle)
	 */
	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.join_activity);
		
		mActivity = this;

		mEtId = (EditText) findViewById(R.id.join_activity_et_id);
		mEtPassword = (EditText) findViewById(R.id.join_activity_et_password);
		mEtNickname = (EditText) findViewById(R.id.join_activity_et_nickname);
		
		// 이메일 수동입력
		mEtEmailManual = (EditText)findViewById(R.id.join_activity_et_email_manual);
		
		// 이메일 선택입력
		mLlEmailAuto = (LinearLayout)findViewById(R.id.join_activity_ll_email_auto);
		mEtEmailAuto = (EditText)findViewById(R.id.join_activity_et_email_auto);
		mBEmailAuto = (Button)findViewById(R.id.join_activity_b_email_auto);
		
		mBEmailAuto.setOnClickListener(this);
		
		ImageButton ibNext = (ImageButton) findViewById(R.id.join_activity_ib_next);
		ibNext.setOnClickListener(this);
		
		// 이메일 수동/자동을 위한 컨텍스트 메뉴 등록
		registerForContextMenu(mBEmailAuto);
	}

	/* (non-Javadoc)
	 * @see android.app.Activity#onContextItemSelected(android.view.MenuItem)
	 */
	@Override
	public boolean onContextItemSelected(MenuItem item)
	{
		switch(item.getItemId())
		{
		// 메일을 선택한 경우
		case CONTEXT_MENU_0_GMAIL:
		case CONTEXT_MENU_1_HANMAIL:
		case CONTEXT_MENU_2_HOTMAIL:
		case CONTEXT_MENU_3_NATE:
		case CONTEXT_MENU_4_NAVER:
			mBEmailAuto.setTextColor(Color.parseColor("#333333"));
			mBEmailAuto.setText(item.getTitle());
			break;
		// 직접입력을 선택한 경우
		case CONTEXT_MENU_5_MANUAL:
			new AlertDialog.Builder(this)
			.setTitle(BaseApplication.getConfigPersistent("appsName"))
			.setMessage("e-mail 주소를 직접 입력하시겠습니까?")
			.setPositiveButton("확인", new DialogInterface.OnClickListener()
			{
				@Override
				public void onClick(DialogInterface dialog, int which)
				{
					mLlEmailAuto.setVisibility(View.INVISIBLE);
					mEtEmailManual.setVisibility(View.VISIBLE);
					
					String text = mEtEmailAuto.getText().toString();
					
					if(text.length() != 0)
					{
						text += "@";
					}
					
					mEtEmailManual.setText(text);
					dialog.dismiss();
				}
			})
			.setNegativeButton("다시 선택", new DialogInterface.OnClickListener()
			{
				@Override
				public void onClick(DialogInterface dialog, int which)
				{
					dialog.dismiss();
				}
			})
			.show();
			break;
		}
		
		return false;
	}

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo)
	{
		super.onCreateContextMenu(menu, v, menuInfo);
		
		menu.setHeaderTitle("e-mail 선택");
		menu.add(0, CONTEXT_MENU_0_GMAIL, 0, MAIL_0_GMAIL);
		menu.add(0, CONTEXT_MENU_1_HANMAIL, 0, MAIL_1_HANMAIL);
		menu.add(0, CONTEXT_MENU_2_HOTMAIL, 0, MAIL_2_HOTMAIL);
		menu.add(0, CONTEXT_MENU_3_NATE, 0, MAIL_3_NATE);
		menu.add(0, CONTEXT_MENU_4_NAVER, 0, MAIL_4_NAVER);
		menu.add(0, CONTEXT_MENU_5_MANUAL, 0, MAIL_5_MANUAL);
	}
	
	/* (non-Javadoc)
	 * @see android.view.View.OnClickListener#onClick(android.view.View)
	 */
	@Override
	public void onClick(View v)
	{
		switch(v.getId())
		{
		case R.id.join_activity_ib_next:

			final String userId = mEtId.getText().toString();
			final String password = mEtPassword.getText().toString();
			final String nickName = mEtNickname.getText().toString();

			String emailTemp = "";
			if(mEtEmailManual.getVisibility() == View.VISIBLE)
			{
				emailTemp = mEtEmailManual.getText().toString();
			}
			else
			{
				emailTemp = mEtEmailAuto.getText().toString() + "@" + mBEmailAuto.getText().toString();
			}
			
			int idLength = userId.length();
			int passwordLength = password.length();
			int nicknameLength = nickName.length();
			try
			{
				nicknameLength = nickName.getBytes("EUC-KR").length;
			}
			catch(UnsupportedEncodingException e)
			{
				e.printStackTrace();
			}
			
			if(idLength < 6 || idLength > 16)
			{
				alert("아이디는 6글자에서 16글자까지 가능합니다");
			}
			else if(!isId(userId))
			{
				alert("아이디는 영문소문자, 영문대문자, 숫자만 가능합니다");
			}
			else if(!isId(password))
			{
				alert("비밀번호는 영문자, 숫자만 가능합니다");
			}
			else if(passwordLength < 6 || passwordLength > 16)
			{
				alert("비밀번호는 6글자에서 16글자까지 가능합니다");
			}
			else if(nicknameLength < 4 || nicknameLength > 16 || !isNick(nickName))
			{
				alert("닉네임은 한글기준 2~8글자 또는 영문기준 4~16글자 조합으로 입력하세요 \", |, \\등과 같은 몇가지 특수문자 입력을 제한합니다");
			}
			else if(!isEmail(emailTemp))
			{
				alert("이메일 주소 형식이 정확하지 않습니다");
			}
			else
			{
				userCheck(userId, nickName, password, emailTemp);
			}
			break;
			
		case R.id.join_activity_b_email_auto:
			openContextMenu(v);
			break;
		}
	}

	private void userCheck(final String userId, final String nickName, final String password, final String email)
	{
		DialogInterface.OnClickListener okayListener = new DialogInterface.OnClickListener()
		{
			@Override
			public void onClick(DialogInterface dialog, int which)
			{
				// 사용자 가입체크
				MonthUnsaeCommand.checkJoin(new HttpHandler(mActivity)
				{
					@Override
					public void didSucceed(Object result)
					{
							Bundle extras = new Bundle();
							
							extras.putString("userId", userId);
							extras.putString("password", password);
							extras.putString("nickName", nickName);
							extras.putString("email", email);
							
							// 가입체크에 성공하면 추가정보 입력페이지로 이동
							getNewActivity()
								.setBundle(extras)
								.setTargetActivity(JoinExtraActivity.class)
								.show();
					}
				}, userId, nickName, email);
				
				dialog.dismiss();
			}
		};
		
		DialogInterface.OnClickListener cancelListener = new DialogInterface.OnClickListener()
		{
			@Override
			public void onClick(DialogInterface dialog, int which)
			{
				dialog.dismiss();
			}
		};

		String text = " - 회원가입 정보확인 -<br>" +
				"아이디: " + userId + "<br>" +
				"닉네임: " + nickName + "<br>" +
				"이메일: " + email + "<br><br>" +
				"★주의★<br>" +
				"비밀번호 분실 시, 임시비밀번호 발급을 위해 정확한 이메일 주소를 적어주세요.";
		
		new AlertDialog.Builder(this)
			.setTitle(BaseApplication.getConfigPersistent("appsName"))
			.setMessage(Html.fromHtml(text))
			.setPositiveButton("확인", okayListener)
			.setNegativeButton("취소", cancelListener)
			.show();
	}
	
	/**
	 * 정상적인 형식의 아이디인지를 체크한다.
	 * 
	 * @param id 아디디
	 * @return 정상적인 아이디인지 여부
	 */
	private boolean isId(String id)
	{
		if(id == null)
		{
			return false;
		}
		
		return Pattern.matches("[a-zA-Z0-9]+", id.trim());
	}
	
	/**
	 * 정상적인 형식의 닉네임인지를 체크한다.
	 * 
	 * @param nick 닉네임
	 * @return 정상적인 닉네임인지 여부
	 */
	private boolean isNick(String nick)
	{
		if(nick == null)
		{
			return false;
		}
		
		return Pattern.matches("[^,^:^\\\\]+", nick.trim());
	}
	
	/**
	 * 정상적인 형식의 이메일주소인지를 체크한다.
	 * 
	 * @param email 메일주소
	 * @return 정상적인 메일주소인지 여부
	 */
	private boolean isEmail(String email)
	{
		if(email == null)
		{
			return false;
		}

		return Pattern.matches("[\\w\\~\\-\\.]+@[\\w\\~\\-]+(\\.[\\w\\~\\-]+)+", email.trim());
	}

	/* (non-Javadoc)
	 * @see com.starpl.platform.common.base.BaseActivity#onCreateOptionsMenu(android.view.Menu)
	 */
	@Override
	public boolean onCreateOptionsMenu(Menu menu)
	{
		return false;
	}

	/* (non-Javadoc)
	 * @see com.starpl.platform.common.base.BaseActivity#onOptionsItemSelected(android.view.MenuItem)
	 */
	@Override
	public boolean onOptionsItemSelected(MenuItem item)
	{
		return false;
	}
}
